
﻿<h1>Function Declarations and Function Calls</h1>

<p>
Except the operator operations introduced in the last article,
function operations are another kind of popular operations in programming.
Function operations are often called function calls.
This article will introduce how to declare functions and call functions.
</p>

<a class="anchor" id="declaration"></a>
<h3>Function Declarations</h3>

<div>
Let's view a function declaration.
<pre class="line-numbers"><code class="language-go">func SquaresOfSumAndDiff(a int64, b int64) (s int64, d int64) {
	x, y := a + b, a - b
	s = x * x
	d = y * y
	return // <=> return s, d
}
</code></pre>

We can find that, a function declaration is composed of several portions.
From left to right,

<ol>
<li>
	the first portion is the <code>func</code> keyword.
</li>
<li>
	the next portion is the function name, which must be an identifier.
	Here the function name is <code>SquareOfSumAndDiff</code>.
</li>
<li>
	the third portion is the input parameter declaration list,
	which is enclosed in a pair of <code>()</code>.
</li>
<li>
	the fourth portion is the output (or return) result declaration list.
	Go functions can return multiple results.
	For this specified example,
	the result definition list is also enclosed in a pair of <code>()</code>.
	However, for some cases, <code>()</code> in result definition lists
	are optional (see below for details).
</li>
<li>
	the last portion is the function body,
	which is enclosed in a pair of <code>{}</code>.
	In a function body,
	the <code>return</code> keyword is used to end the normal forward execution flow
	and enter the exiting phase (see the section after next) of a call of the function.
</li>
</ol>


<p>
In the above example, each parameter and result declaration is composed of
a name and a type (the type follows the name).
We can view parameter and result declarations as standard variable declarations
without the <code>var</code> keywords.
The above declared function has two parameters, <code>a</code> and <code>b</code>,
and has two results, <code>s</code> and <code>d</code>.
All the types of the parameters and results are <code>int64</code>.
Parameters and results are treated as local variables within
their corresponding function bodies.
</p>

<p>
The names in the result declaration list of a function declaration can/must be
present or absent all together. Either case is used common in practice.
If a result is defined with a name, then the result is called a named result,
otherwise, it is called an anonymous result.
</p>

When all the results in a function declaration are anonymous,
then, within the corresponding function body,
the <code>return</code> keyword must be followed by a sequence of return values,
each of them corresponds to a result declaration of the function declaration.
For example, the following function declaration is equivalent to the above one.
<pre class="line-numbers"><code class="language-go">func SquaresOfSumAndDiff(a int64, b int64) (int64, int64) {
	return (a+b) * (a+b), (a-b) * (a-b)
}
</code></pre>

<p>
</p>

<p>
In fact, if all the parameters are never used within the corresponding function body,
the names in the parameter declaration list of a function declaration
can be also be omitted all together.
However, anonymous parameters are rarely used in practice.
</p>

<p>
Although it looks the parameter and result variables are declared
outside of the body of a function declaration, they are viewed as
general local variables within the function body.
The difference is that local variables with non-blank names declared
within a function body must be ever used in the function body.
Non-blank names of top-level local variables, parameters and results
in a function declaration can't be duplicated.
</p>

Go doesn't support default parameter values.
The initial value of each result is the zero value of its type.
For example, the following function will always print (and return) <code>0 false</code>.
<pre class="line-numbers"><code class="language-go">func f() (x int, y bool) {
	println(x, y) // 0 false
	return
}
</code></pre>

<p>
</p>

If the types of some successive parameters or results in a function declaration
are the same one, then the types of the former parameters or results can be absent.
For example, the above two function declarations with the name <code>SquaresOfSumAndDiff</code> are equivalent to
<pre class="line-numbers"><code class="language-go">func SquaresOfSumAndDiff(a, b int64) (s, d int64) {
	return (a+b) * (a+b), (a-b) * (a-b)
	// The above line is equivalent
	// to the following line.
	/*
	s = (a+b) * (a+b); d = (a-b) * (a-b); return
	*/
}
</code></pre>

<p>
Please note, even if both the two results are named,
the <code>return</code> keyword can be followed with return values.
</p>

<p>
If the result declaration list in a function declaration only contains
one anonymous result declaration,
then the result declaration list doesn't need to be enclosed in a <code>()</code>.
If the function declaration has no return results,
then the result declaration list portion can be omitted totally.
The parameter declaration list portion can never be omitted,
even if the number of parameters of the declared function is zero.
</p>

Here are more function declaration examples.
<pre class="line-numbers"><code class="language-go">func CompareLower4bits(m, n uint32) (r bool) {
	r = m&0xF > n&0xF
	return
	// The above two lines is equivalent to
	// the following line.
	/*
	return m&0xF > n&0xF
	*/
}

// This function has no parameters.
func VersionString() string {
	return "go1.0"
}

// This function has no results. And all of
// its parameters are anonymous, for we
// don't care about them.
func doNothing(string, int) {
}
</code></pre>

<p>
</p>

<p>
One fact we have learned from the earlier articles in Go 101 is that
the <code>main</code> entry function in each Go program is declared
without parameters and results.
</p>

<p>
Please note that, functions must be directly declared at package level.
In other words, a function can't be declared within the body of another function.
In a later section, we will learn that we can define anonymous functions in bodies of other functions.
But anonymous functions are not function declarations.
</p>
</div>

<a class="anchor" id="call"></a>
<h3>Function Calls</h3>

<div>

<p>
A declared function can be called through its name plus an argument list.
The argument list must be enclosed in a <code>()</code>.
Each single-value argument corresponds to a parameter declaration.
</p>

<p>
The type of an argument is not required to be identical with the corresponding parameter type.
The only requirement for the argument is
it must be <a href="constants-and-variables.html#assignment">assignable</a>
(a.k.a., implicitly convertible) to the corresponding parameter type.
</p>

The following is a full example to show how to call some declared functions.

<pre class="line-numbers"><code class="language-go">package main

func SquaresOfSumAndDiff(a int64, b int64) (int64, int64) {
	return (a+b) * (a+b), (a-b) * (a-b)
}

func CompareLower4bits(m, n uint32) (r bool) {
	r = m&0xF > n&0xF
	return
}

// Initialize a package-level variable
// with a function call.
var v = VersionString()

func main() {
	println(v) // v1.0
	x, y := SquaresOfSumAndDiff(3, 6)
	println(x, y) // 81 9
	b := CompareLower4bits(uint32(x), uint32(y))
	println(b) // false
	// "Go" is deduced as a string,
	// and 1 is deduced as an int32.
	doNothing("Go", 1)
}

func VersionString() string {
	return "v1.0"
}

func doNothing(string, int32) {
}
</code></pre>

<p>
From the above example, we can learn that a function can be either declared
before or after any of its calls.
</p>
</div>

<p>
Function calls can be deferred or invoked in new goroutines (green threads) in Go.
Please read <a href="control-flows-more.html">a later article</a> for details.
</p>

<a class="anchor" id="exiting-phase"></a>
<h3>Exiting Phase of a Function Call</h3>

<p>
In Go, a function call may undergo an exiting phase.
The exiting phase of a function call starts when the called function is returned.
In other words, when a function call is returned, it is possible that it hasn't exited yet.
We will learn what is the exiting phase of a function call in the article
mentioned at the end of the last seciton.
</p>

<p>
More detailed explanations for exiting phases of function calls can be found in
<a href="panic-and-recover-more.html#exiting-phase">this article</a>.
</p>

<h3>Anonymous Functions</h3>

<div>
<p>
Go supports anonymous functions.
The definition of an anonymous function is almost the same as a function
declaration, except there is no function name portion in
the anonymous function definition.
</p>

An anonymous function can be called right after it is defined.
Example:
<pre class="line-numbers"><code class="language-go">package main

func main() {
	// This anonymous function has no parameters
	// but has two results.
	x, y := func() (int, int) {
		println("This function has no parameters.")
		return 3, 4
	}() // Call it. No arguments are needed.

	// The following anonymous function have no results.

	func(a, b int) {
		// The following line prints: a*a + b*b = 25
		println("a*a + b*b =", a*a + b*b)
	}(x, y) // pass argument x and y to parameter a and b.

	func(x int) {
		// The parameter x shadows the outer x.
		// The following line prints: x*x + y*y = 32
		println("x*x + y*y =", x*x + y*y)
	}(y) // pass argument y to parameter x.

	func() {
		// The following line prints: x*x + y*y = 25
		println("x*x + y*y =", x*x + y*y)
	}() // no arguments are needed.
}
</code></pre>

<p>
</p>

<p>
Please note that, the last anonymous function is in the scope of
the <code>x</code> and <code>y</code> variables declared above,
it can use the two variables directly.
Such functions are called closures.
In fact, all custom functions in Go can be viewed as closures.
This is why Go functions are as flexible as many dynamic languages.
</p>

<p>
Later, we will learn that an anonymous function can be assigned
to a function value and can be called at any time.
</p>

</div>

<h3>Built-in Functions</h3>

<div>
<p>
There are some built-in functions in Go,
for example, the <code>println</code> and <code>print</code> functions.
We can call these functions without importing any packages.
</p>

<p>
We can use the built-in <code>real</code> and <code>imag</code> functions
to get the real and imaginary parts of a complex value.
We can use the built-in <code>complex</code> function to produce a complex value.
Please note, if any of the arguments of a call to any of the two functions
are all constants, then the call will be evaluated at compile time,
and the result value of the call is also a constant.
In particular, if any of the arguments is an untyped constant,
then the result value is also an untyped constant.
The call is viewed as a constant expression.
</p>

Example:
<pre class="line-numbers"><code class="language-go">// c is a untyped complex constant.
const c = complex(1.6, 3.3)

// The results of real(c) and imag(c) are both
// untyped floating-point values. They are both
// deduced as values of type float32 below.
var a, b float32 = real(c), imag(c)

// d is deduced as a typed value of type complex64.
// The results of real(d) and imag(d) are both
// typed values of type float32.
var d = complex(a, b)

// e is deduced as a typed value of type complex128.
// The results of real(e) and imag(e) are both
// typed values of type float64.
var e = c
</code></pre>

<p>
More built-in functions will be introduced in other Go 101 articles later.
</p>
</div>

<h3>More About Functions</h3>

<p>
There are more about function related concepts and details
which are not touched in the current article.
We can learn those concepts and details in the article
<a href="function.html">function types and values</a> later.
</p>


